﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Threading.Tasks;
using WalkingTec.Mvvm.Core;
using WalkingTec.Mvvm.Mvc;
using WalkingTec.Mvvm.Core.Extensions;
using System.Linq;
using System.Collections.Generic;
using nERP.Model.Bas;
using nERP.ViewModel.Bas.CodingListVMs;
using nERP.Model;

namespace nERP.Bas.Controllers
{
    [AuthorizeJwtWithCookie]
    [ActionDescription("_Model.CodingList")]
    [ApiController]
    [Route("/api/Bas/CodingList")]
    public partial class CodingListController : BaseApiController
    {
        [ActionDescription("Sys.Get")]
        [HttpGet("{id}")]
        public IActionResult Get(string id)
        {
            var vm = Wtm.CreateVM<CodingListVM>(id);
            return Ok(vm);
        }

        [ActionDescription("Sys.Create")]
        [HttpPost("[action]")]
        public async Task<IActionResult> Create(CodingListVM vm)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState.GetErrorJson());
            }
            else
            {
                await vm.DoAddAsync();

                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState.GetErrorJson());
                }
                else
                {
                    return Ok(vm.Entity);
                }
            }

        }

        [ActionDescription("Sys.Edit")]
        [HttpPut("[action]")]
        public async Task<IActionResult> Edit(CodingListVM vm)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState.GetErrorJson());
            }
            else
            {
                await vm.DoEditAsync(false);
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState.GetErrorJson());
                }
                else
                {
                    return Ok(vm.Entity);
                }
            }
        }


        [HttpPost("BatchEdit")]
        [ActionDescription("Sys.BatchEdit")]
        public ActionResult BatchEdit(CodingListBatchVM vm)
        {
            if (!ModelState.IsValid || !vm.DoBatchEdit())
            {
                return BadRequest(ModelState.GetErrorJson());
            }
            else
            {
                return Ok(vm.Ids.Count());
            }
        }

        [HttpPost("BatchDelete")]
        [ActionDescription("Sys.Delete")]
        public IActionResult BatchDelete(string[] ids)
        {
            var vm = Wtm.CreateVM<CodingListBatchVM>();
            if (ids != null && ids.Count() > 0)
            {
                vm.Ids = ids;
            }
            else
            {
                return Ok();
            }
            if (!ModelState.IsValid || !vm.DoBatchDelete())
            {
                return BadRequest(ModelState.GetErrorJson());
            }
            else
            {
                return Ok(ids.Count());
            }
        }

        [ActionDescription("Sys.DownloadTemplate")]
        [HttpGet("GetExcelTemplate")]
        public IActionResult GetExcelTemplate()
        {
            var vm = Wtm.CreateVM<CodingListImportVM>();
            var qs = new Dictionary<string, string>();
            foreach (var item in Request.Query.Keys)
            {
                qs.Add(item, Request.Query[item]);
            }
            vm.SetParms(qs);
            var data = vm.GenerateTemplate(out string fileName);
            return File(data, "application/vnd.ms-excel", fileName);
        }

        [ActionDescription("Sys.Import")]
        [HttpPost("Import")]
        public ActionResult Import(CodingListImportVM vm)
        {

            if (vm.ErrorListVM.EntityList.Count > 0 || !vm.BatchSaveData())
            {
                return BadRequest(vm.GetErrorJson());
            }
            else
            {
                return Ok(vm.EntityList.Count);
            }
        }

        [AllRights]
        [ActionDescription("获取单据流水")]
        [HttpGet("GetNewSN")]
        public string GetNewSN(string Code, bool readolny = true, IDataContext dc = null)
        {
            if (dc == null) dc = DC;
            string SN = "";
            var entity = dc.Set<CodingList>().Where(x => x.Code == Code).FirstOrDefault();
            if (entity == null || string.IsNullOrWhiteSpace(entity.Code))
            {
                Code = "通用";//通用编码规则：年份1码+8位流水号
                entity = dc.Set<CodingList>().Where(x => x.Code == Code).FirstOrDefault();
                if (entity == null || string.IsNullOrWhiteSpace(entity.Code))
                {
                    entity = new CodingList() { ID = Guid.NewGuid(), Code = Code, CurrentNumber = 0, IsValid = true, CreateBy = "Admin", CreateTime = DateTime.Now };

                    List<CodingRule> codingrule = new List<CodingRule>() {
                        new CodingRule() { ID = Guid.NewGuid(), CodingListId = Code, Seq = 1, CodeRule = CodeRuleEnum.RuleFixed, FixedValue = null, FixedRule = FixedEnum.y, GlideLen=null, StartNumber = 1, GlideStep = 1, Glide = "0", },
                        new CodingRule() { ID = Guid.NewGuid(), CodingListId = Code, Seq = 2, CodeRule = CodeRuleEnum.Serial, FixedValue = null, FixedRule = null,GlideLen=8, StartNumber = 1, GlideStep = 1, Glide = "0", },
                };

                    dc.AddEntity(entity);
                    dc.SaveChanges();
                    dc.Set<CodingRule>().AddRange(codingrule);
                    dc.SaveChanges();
                    //return DateTime.Now.ToString("yyyyMMddHHmmssfff");
                }
            }

            entity.CurrentNumber++;
            var CodingRule = dc.Set<CodingRule>().Where(x => x.CodingListId == Code).OrderBy(c => c.Seq).ToList();
            if (CodingRule?.Count > 0)
            {
                foreach (var item in CodingRule)
                {
                    //规则=固定值
                    if (item.CodeRule == CodeRuleEnum.Fixeds)
                    {
                        SN += item.FixedValue;
                    }
                    //规则=时间规则值
                    if (item.CodeRule == CodeRuleEnum.RuleFixed)
                    {
                        if (string.IsNullOrWhiteSpace(item.FixedRule.ToString())) return DateTime.Now.ToString("yyyyMMddHHmmssfff");
                        if (item.FixedRule == FixedEnum.y)
                            SN += DateTime.Now.Year.ToString().Substring(3);//年份最后一位
                        else
                            SN += DateTime.Now.ToString(item.FixedRule.ToString());
                    }
                    //规则=流水号
                    if (item.CodeRule == CodeRuleEnum.Serial)
                    {
                        if (entity.CurrentNumber == null || item.GlideLen == null || entity.CurrentNumber < 1 || string.IsNullOrWhiteSpace(item.Glide) || item.GlideLen < 1)
                            return DateTime.Now.ToString("yyyyMMddHHmmssfff");
                        System.Text.StringBuilder sb = new System.Text.StringBuilder();
                        System.Text.StringBuilder sb2 = new System.Text.StringBuilder();
                        for (int i = 0; i < item.GlideLen; i++)
                        {
                            sb.Append(item.Glide);
                            sb2.Append("9");
                        }
                        //如果当前流水号>流水最大数，将当前流水号=1
                        long maxNumber = long.Parse(sb2.ToString());
                        if (entity.CurrentNumber > maxNumber) entity.CurrentNumber = 1;
                        SN += entity.CurrentNumber?.ToString(sb.ToString());
                    }
                }
            }
            entity.Example = SN;
            entity.UpdateBy = Wtm.LoginUserInfo.Name;
            entity.UpdateTime = DateTime.Now;
            if (!readolny) { dc.UpdateEntity(entity); dc.SaveChanges(); }


            return SN ?? DateTime.Now.ToString("yyyyMMddHHmmssfff");

        }



    }
}